package com.iwat.hellospringboot.controller;

import com.iwat.hellospringboot.service.NotificationService;
import org.springframework.messaging.handler.annotation.MessageMapping;
import org.springframework.messaging.handler.annotation.SendTo;
import org.springframework.stereotype.Controller;

/**
 * @author 王伟强
 * @date 2024/5/6 14:11
 */

@Controller
public class GreetingController {
    private NotificationService notificationService;

    public GreetingController(NotificationService notificationService) {
        this.notificationService = notificationService;
    }

    /**
     * `@MessageMapping 用于接收客户端发送的消息
     * `@SendTo 用于向客户端【/topic/greetings】发送消息，此时【/topic/greetings】客户端会监听到返回值
     * @param message 客户端发送的消息
     * @return 返回给客户端的消息
     * @throws Exception 异常
     */
    @MessageMapping("/hello")
    @SendTo("/topic/greetings")
    public String greeting(String message) throws Exception {
        return "Hello, " + message + "!";
    }

    /**
     * 不使用@SendTo("/topic/greetings")
     * @param message 客户端发送的消息
     * @throws Exception 异常
     */
    @MessageMapping("/handle")
    public void handler(String message) throws Exception {
        notificationService.handle(message);
    }
}
